import time

from selenium.webdriver.common.by import By
from base.page_base import BasePage


class LoanManager(BasePage):
    """额度审核功能封装"""

    # 元素定位器
    # 1.后台管理菜单
    __loan = By.LINK_TEXT, "借款管理"
    __limit = By.XPATH, '//span[text()="额度管理"]'
    __app_review = (By.LINK_TEXT, "额度申请审核")
    # 2.记录搜索
    __frame1 = (By.ID, "iframe_box")
    __username = By.NAME, 'member_name'  # 用户名
    __search_btn = By.CSS_SELECTOR, '[value="搜索"]'  # 搜索按钮
    # 3.选中记录审核
    __record = By.XPATH, '//tbody/tr[1]/td[2]/span'  # 选中第一条
    __approve = By.XPATH, '//span[text()="审核"]'  # 审核按钮
    # 4.审核操作
    __frame2 = (By.CSS_SELECTOR, "#xubox_iframe1")
    __radio = By.CSS_SELECTOR, '.ace.ng-pristine.ng-untouched.ng-valid'  # 通过
    __note = By.CSS_SELECTOR, 'tr:nth-child(6) > td:nth-child(2) > div > textarea'  # 备注
    __img_code = By.NAME, 'valicode'  # 验证码
    __save = By.CSS_SELECTOR, '.dybtn.dybtn-save'  # 保存
    # 5.审核记录
    __app_rec = (By.LINK_TEXT, "额度申请记录")  # 额度申请记录
    # 搜索：用户名 + 状态 + 搜索按钮
    __app_status = By.CSS_SELECTOR, "select[name='status']"  # 状态
    # 审核列表状态：通过
    __rec_list = By.CSS_SELECTOR, "tbody > tr:nth-child(1) > td.status > span"

    def click_menu_manage(self):
        """点击管理菜单"""
        self.base_click(self.__loan)
        self.base_click(self.__limit)
        self.base_click(self.__app_review)

    def search_record(self, phone):
        """搜索记录"""
        self.base_switch_frame(self.__frame1)
        self.base_input(self.__username, phone)
        self.base_click(self.__search_btn)

    def click_record(self):
        """点击记录"""
        time.sleep(1)  # 页面刷新，看到新记录
        self.base_click(self.__record)
        self.base_click(self.__approve)

    def approve_loan(self, note="审核OK", img_code="8888"):
        """审核操作"""
        self.base_switch_frame(self.__frame2)
        self.base_click_special(self.__radio)
        self.base_input(self.__note, note)
        self.base_input(self.__img_code, img_code)
        self.base_click(self.__save)

    def click_app_rec(self, phone, status="通过"):
        """点击额度申请记录"""
        self.base_default_frame()  # 切换到默认frame
        self.base_click(self.__app_rec)  # 点击额度申请记录
        self.base_switch_frame(self.__frame1)  # 切换另一个frame
        self.base_input(self.__username, phone)
        self.base_select_list(self.__app_status, status)
        self.base_click(self.__search_btn)

    def get_result_text(self):
        """获取审核结果"""
        time.sleep(1)  # 页面刷新，看到新记录
        return self.fd_element(self.__rec_list).text  # 获取当前审核结果文本

    def credit_application_review(self, phone, note="审核OK", img_code="8888"):
        """业务：额度申请审核"""
        self.click_menu_manage()
        self.search_record(phone)
        self.click_record()
        self.approve_loan(note, img_code)
